package com.gexiaobao.pigeon.ui.fragment.mine.banking

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Window
import android.view.WindowManager
import androidx.core.content.ContextCompat
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.setFragmentResultListener
import androidx.lifecycle.lifecycleScope
import cn.qqtheme.framework.picker.SinglePicker
import cn.qqtheme.framework.widget.WheelView
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.countDownCoroutines
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.QueryBalanceResponse
import com.gexiaobao.pigeon.app.model.bean.QueryBankListResponse
import com.gexiaobao.pigeon.app.model.param.DepositApplyParam
import com.gexiaobao.pigeon.app.model.param.DepositApplySDKParam
import com.gexiaobao.pigeon.app.model.param.PayParam
import com.gexiaobao.pigeon.app.tools.tongliansdk.TonglianSdk.openPay
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.databinding.FragmentAccountRechargeBinding
import com.gexiaobao.pigeon.ui.dialog.PayPassDialog
import com.gexiaobao.pigeon.ui.dialog.PayPassView
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.dialog.RxDialogRechargeRule
import com.gexiaobao.pigeon.ui.dialog.RxPayDialog
import com.gexiaobao.pigeon.ui.fragment.mine.banking.activity.ActivityBankLimit
import com.gexiaobao.pigeon.viewmodel.MineBankingViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import java.math.BigDecimal

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 19:36
 * @Describe    : 充值
 */
class FragmentAccountRecharge : BaseFragment<MineBankingViewModel, FragmentAccountRechargeBinding>() {

    private var gebiDesc: String = ""
    private var bankCardInfo: ArrayList<QueryBankListResponse.ListBean> = arrayListOf()
    private var payDialog: RxPayDialog? = null
    private var mPosition = 0//记录上次选中位置
    private var mOrderId: Int = 0
    private var investMoneyBean: QueryBankListResponse.ListBean? = null
    private var isResendCode: Boolean = false
//    private var isBindCard = false

    override fun initView(savedInstanceState: Bundle?) {
//        isBindCard = requireArguments().getBoolean("isBindCard")
        mDatabind.viewmodel = mViewModel
        mDatabind.includeBar.toolbar.initClose("充值") {
            nav().navigateUp()
        }
        mDatabind.includeBar.tvRightMenu.text = "限额说明"
        mDatabind.includeBar.tvRightMenu.background = ContextCompat.getDrawable(requireContext(), R.drawable.round_tv_red_stroke20_bg)

        mPosition = KvUtils.decodeInt("position")!!
        investMoneyBean = QueryBankListResponse.ListBean()
        mViewModel.queryBalance()
//        val mData = arguments?.getParcelable<QueryBalanceResponse>(Constant.DATA_BEAN)
//        if (mData != null) {
//            setDataUI(mData)
//        }

        setFragmentResultListener("ok") { _, bundle ->
            if (bundle.getBoolean("isS")) {
                onRefresh()
            }
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        onRefresh()
    }

    private fun onRefresh() {
        showLoadingAntiShake(getString(R.string.loading))
        mViewModel.queryBankCard()
    }

    private fun setDataUI(it: QueryBalanceResponse) {
        gebiDesc = it.gebiDesc
        mViewModel.gebiBalances.set(it.gebiCnt.toString())
        mViewModel.allAmount.set(SettingUtil.div(it.allAmount, 100.00, 2).toString())
        mViewModel.availableBalances.set(
            SettingUtil.div(it.allAmount - it.freezenAmount, 100.00, 2).toString()
        )
        mViewModel.blockedBalances.set(SettingUtil.div(it.freezenAmount, 100.00, 2).toString())
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.selectBankCard,
            mDatabind.addBankCard,
            mDatabind.investMoneyCommit,
            mDatabind.ivRechargeRuleContent,
            mDatabind.includeBar.tvRightMenu
        ) {
            when (it) {
                mDatabind.includeBar.tvRightMenu -> {
                    startActivity<ActivityBankLimit>()
                }

                mDatabind.selectBankCard -> {
//                    if (isBindCard) {
                    selectedBank(bankCardInfo)
//                    } else {
//                        nav().navigateAction(R.id.action_to_account_setting_process, Bundle().apply {
//                            putString(Constant.INTO_TYPE, "mineBank")
//                        })
//                    }
                }

                mDatabind.addBankCard -> {
                    nav().navigateAction(R.id.action_to_account_add_bank_card)
                }

                mDatabind.investMoneyCommit -> {
                    isResendCode = false
                    moneyCommit()
                }

                mDatabind.ivRechargeRuleContent -> {
                    showRuleDialog()
                }
            }
        }
    }

    private fun showRuleDialog() {
        val dialog = RxDialogRechargeRule(context)
        dialog.setTitle("鸽币使用须知")
        dialog.setContent(gebiDesc)
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun moneyCommit() {
        val payFor = mDatabind.investMoney.text.toString()
        when {
            payFor.isEmpty() -> showMessage("请输入充值金额")
            payFor.toIntOrNull()!! < 100 || payFor.toIntOrNull()!! % 100 != 0 -> showMessage(
                getString(
                    R.string.activity_mine_account_invest_money_cannot_lower_100
                )
            )

            !mDatabind.radioBtnCodePay.isChecked && !mDatabind.radioBtnBankPay.isChecked -> showMessage(
                "请选择支付方式"
            )

            else -> {
                if (mDatabind.radioBtnCodePay.isChecked) {
                    val body = investMoneyBean?.let { it1 ->
                        DepositApplyParam(
                            bankCardNo = it1.bankCardNo,
                            money = (mDatabind.investMoney.text.toString().toDouble() * 100).toInt()
                        )
                    }
                    showLoadingAntiShake(getString(R.string.loading))
                    body?.let { it1 -> mViewModel.depositApply(it1) }
                } else {
                    showLoadingAntiShake(getString(R.string.loading))
                    val amt = mDatabind.investMoney.text.toString()
                    val money = BigDecimal(amt).multiply(BigDecimal(100)).toBigInteger().toInt()
                    val param = DepositApplySDKParam(money = money)
                    mViewModel.depositApplySDK(param)
                }
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 充值获取鸽币信息 */
        mViewModel.gebiInfoResult.observe(viewLifecycleOwner) {
            mViewModel.queryBalance()
        }
        /** 查询余额 */
        mViewModel.queryBalanceResult.observe(viewLifecycleOwner) { resultState ->
            parseState(resultState, {
                setDataUI(it)
            }, {
                RxToast.showToast(it.msg)
            })
        }
        mViewModel.depositApplySDKResult.observe(viewLifecycleOwner) { resultState ->
            dismissLoadingAntiShake()
            parseState(resultState, {
                activity?.let { it1 ->
                    openPay(
                        it1,
                        it.amount.toString(),
                        notifyurl = it.notifyurl,
                        validtime = it.validtime.toString(),
                        reqsn = it.reqsn
                    )
                }
            }, {
                RxToast.showToast(it.msg)
            })
        }
        mViewModel.queryBankListResult.observe(viewLifecycleOwner) {
            if (!it.isEmpty) {
                if (it.listData?.isNotEmpty() == true) {
                    bankCardInfo.addAll(it.listData)
                    if (mPosition <= it.listData.size - 1) {
                        investMoneyBean = QueryBankListResponse.ListBean(
                            bankCardNo = it.listData[mPosition].bankCardNo,
                            bankName = it.listData[mPosition].bankName,
                            bindTime = it.listData[mPosition].bindTime,
                            cardType = it.listData[mPosition].cardType,
                            bindState = it.listData[mPosition].bindState
                        )
                    } else {
                        investMoneyBean = QueryBankListResponse.ListBean(
                            bankCardNo = it.listData.last().bankCardNo,
                            bankName = it.listData.last().bankName,
                            bindTime = it.listData.last().bindTime,
                            cardType = it.listData.last().cardType,
                            bindState = it.listData.last().bindState
                        )
                    }
                    mDatabind.data = investMoneyBean
                }
            }
        }

        /** 充值 */
        mViewModel.depositApplyResult.observe(viewLifecycleOwner) { resultState ->
            dismissLoadingAntiShake()
            parseState(resultState, {
                mOrderId = it.orderId
                if (!isResendCode) {
                    showPayDialog()
                }
            }, {
                RxToast.showToast(it.msg)
            })
        }

        mViewModel.payResult.observe(viewLifecycleOwner) { resultState ->
            parseState(resultState, {
                mViewModel.getChargeGebiInfo(mDatabind.investMoney.text.toString().toInt())
                payPassDialog?.dismiss()
                if (payDialog != null && payDialog!!.isShowing)
                    payDialog?.showBottomView()
                workWithResponseData()
            }, {
                RxToast.showToast(it.msg)
                payDialog?.dismiss()
            })
        }
    }

    @SuppressLint("SetTextI18n")
    private fun workWithResponseData() {
        payDialog?.successAnimDialog()
        payDialog?.setDialogContent("充值成功")
        job = countDownCoroutines(3, {
            payDialog?.sureView?.text = "($it)秒后自动返回"
        }, {
            payDialog?.dismiss()
            onBackToMineBankPage()
            job?.cancel()
        }, lifecycleScope)
        payDialog?.setCancelBtnContent("立即返回")
    }

    private fun onBackToMineBankPage() {
        setFragmentResult("RechargeIsOk", Bundle().apply {
            putBoolean("isOK", true)
        })
        nav().navigateUp()
    }

    var payPassDialog: PayPassDialog? = null

    @SuppressLint("SetTextI18n")
    private fun showPayDialog() {
        payPassDialog = PayPassDialog(context)
        val textWatcherListener = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null) {
                    val str = "" + s
                    if (str.length == 6) {
                        if (payPassDialog != null) {
                            val split = str.trim().replace(" ", "").split("")
                            if (split.size == 6) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[0]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[5]
                                payPassDialog!!.payViewPass.strPass = str
                            } else if (split.size == 8) {
                                payPassDialog!!.payViewPass.mTvPass[0].text = "" + split[1]
                                payPassDialog!!.payViewPass.mTvPass[1].text = "" + split[2]
                                payPassDialog!!.payViewPass.mTvPass[2].text = "" + split[3]
                                payPassDialog!!.payViewPass.mTvPass[3].text = "" + split[4]
                                payPassDialog!!.payViewPass.mTvPass[4].text = "" + split[5]
                                payPassDialog!!.payViewPass.mTvPass[5].text = "" + split[6]
                                payPassDialog!!.payViewPass.strPass = str
                            }
                        }
                    }
                }
            }
        }
        payPassDialog!!.payViewPass.mTvPass[0].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[1].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[2].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[3].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[4].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.mTvPass[5].addTextChangedListener(textWatcherListener)
        payPassDialog!!.payViewPass.setPayClickListener(object : PayPassView.OnPayClickListener {
            override fun onPaySubmit() {}

            override fun onPayClose() {
                RxToast.showToast("关闭支付")
                payPassDialog!!.dismiss()
            }

            override fun onPayForget() {
                isResendCode = true
                val body = investMoneyBean?.let { it1 ->
                    DepositApplyParam(
                        bankCardNo = it1.bankCardNo,
                        money = (mDatabind.investMoney.text.toString().toDouble() * 100).toInt()
                    )
                }
                body?.let { it1 -> mViewModel.depositApply(it1) }
            }

            override fun onPassFinish(verifyCode: String?) {
                showPayAnimDialog()
                job = countDownCoroutines(1, {

                }, {
                    val body = PayParam(mOrderId, verifyCode.toString())
                    mViewModel.commitPay(body)
                }, lifecycleScope)

            }
        })
    }

    private fun showPayAnimDialog() {
        payDialog = RxPayDialog(context)
        payDialog!!.loadingDialog()
        payDialog!!.cancelView.setOnClickListener {
            job?.cancel()
            payDialog!!.dismiss()
        }
        payDialog!!.setCanceledOnTouchOutside(false)
        payDialog!!.setFullScreenWidth()
        payDialog!!.show()
    }


    private fun selectedBank(bankList: ArrayList<QueryBankListResponse.ListBean>) {
        if (bankList.isNotEmpty()) {
            val picker = SinglePicker(activity, bankList)
            picker.setCanceledOnTouchOutside(false)
            picker.setDividerRatio(WheelView.DividerConfig.FILL)
            picker.setShadowColor(Color.rgb(9, 155, 251), 40)
            picker.setCycleDisable(true)
            picker.setTitleText("请选择银行卡")
            picker.setTitleTextColor(Color.BLACK)
            picker.setTitleTextSize(18)
            picker.setSubmitText("确认")
            picker.setSubmitTextSize(17)
            picker.setSubmitTextColor(Color.rgb(9, 155, 251))//确定按钮文字颜色
            picker.setCancelText("取消")
            picker.setCancelTextSize(17)
            picker.setCancelTextColor(Color.rgb(9, 155, 251))//取消按钮文字颜色
            picker.setTextSize(18)
            picker.setLineSpaceMultiplier(3.0F)
            picker.setOnItemPickListener { index, item ->
                KvUtils.encode("position", index)
                investMoneyBean =
                    QueryBankListResponse.ListBean(
                        bankCardNo = item.bankCardNo,
                        bankName = item.bankName,
                        bindTime = item.bindTime,
                        cardType = item.cardType,
                        bindState = item.bindState
                    )
                mDatabind.data = investMoneyBean
            }
            val window: Window = picker.window
            val lp: WindowManager.LayoutParams = window.attributes
            lp.width = WindowManager.LayoutParams.MATCH_PARENT
            picker.setWidth(WindowManager.LayoutParams.MATCH_PARENT)
            picker.show()
        }
    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if (requestCode === Allinpay.REQUEST_CODE_PAY) {
//            if (resultCode === RESULT_OK) {
//                val retCode = data!!.getIntExtra("retCode", Allinpay.ALLINPAY_UNKNOWN)
//                val retErrmsg = data.getStringExtra("retErrmsg")
//                // 订单id
//                val orderId = data.getStringExtra("orderId")
//                // 订单状态，具体状态说明见文档
//                val trxStatus = data.getStringExtra("trxStatus")
//                // 订单状态说明
//                val trxErrmsg = data.getStringExtra("trxErrmsg")
//            }
//        }
//    }
}